package com.ck.websocket.controller;

import com.ck.websocket.entity.RequestMessage;
import com.ck.websocket.entity.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 被订阅的频道
     */
    public static final String SUBSCRIBE = "/topic/message";

    public static final String SUBSCRIBE_TWO = "/topic/route/message";

    @MessageMapping("/ws") // @MessageMapping 和 @RequestMapping 功能类似，浏览器向服务器发起消息，映射到该地址。
    @SendTo(SUBSCRIBE)//当服务器有消息需要推送的时候，会对订阅了@SendTo中路径的浏览器发送消息
    public String say(String message) throws Exception {
        System.out.println(111);
        return message;
    }

    @SendTo(SUBSCRIBE_TWO)//当服务器有消息需要推送的时候，会对订阅了@SendTo中路径的浏览器发送消息
    public String route(String message) throws Exception {
        System.out.println(111);
        return message;
    }

    /**
     * @title http请求产生消息，并推送
     * @param message
     * @return
     * @throws IOException
     */
    @PostMapping("/http")
    public String send(@RequestBody RequestMessage message) throws IOException {
        System.out.println(message.getMessage());
        simpMessagingTemplate.convertAndSend(SUBSCRIBE,new ResponseMessage(message.toString()) );
        return "success";
    }

    @PostMapping("/route")
    public String send_route(@RequestBody RequestMessage message) throws IOException {
        System.out.println(message.getMessage());
        simpMessagingTemplate.convertAndSend(SUBSCRIBE_TWO,new ResponseMessage(message.toString()) );
        return "success";
    }
}